/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.tarifador.dao;

import br.com.tarifador.autenticacao.CriptografaSenha;
import br.com.tarifador.model.Usuario;
import br.com.tarifador.util.HibernateUtil;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.jboss.logging.Logger;

/**
 *
 * @author charles
 */
public class TarifadorDao<T> implements impleTarifa<T> {

    private CriptografaSenha criptrografa;
    private static Session sessao;
    private static Transaction transacao;
    private Class<T> classe;
    private Usuario usuarioTemp;

    public TarifadorDao(Class classes) {
        this.classe = classes;
    }

    @Override
    public boolean update(T objeto) {
        boolean valida;
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            transacao = sessao.beginTransaction();
            sessao.update(objeto);
            transacao.commit();
            valida = true;
            if (sessao.isOpen()) {
                sessao.close();
            }
        } catch (Exception e) {
            valida = false;
            if (sessao.isOpen()) {
                sessao.close();
            }
            throw new HibernateException(e);
        }
        return valida;
    }

    @Override
    public boolean save(T objeto) {
        boolean valida;
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            transacao = sessao.beginTransaction();
            sessao.save(objeto);
            transacao.commit();
            valida = true;
            if (sessao.isOpen()) {
                sessao.close();
            }
        } catch (Exception e) {
            valida = false;
            if (sessao.isOpen()) {
                sessao.close();
            }
            throw new HibernateException(e);
        }
        return valida;
    }

    @Override
    public T findbyString(String param, String campoNome) {
        T objeto = null;

        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            sessao.beginTransaction();
            Criteria criteria = sessao.createCriteria(classe);
            criteria.add(Restrictions.ilike(campoNome, "%" + param + "%"));
       
            objeto = (T) criteria.uniqueResult();
            if (sessao.isOpen()) {
                sessao.close();
            }
        } catch (Exception e) {
            if (sessao.isOpen()) {
                sessao.close();
            }
            throw new HibernateException(e);
        }
        Logger.getLogger(TarifadorDao.class.getName()).log(Logger.Level.INFO, objeto.toString());
        return objeto;
    }

    @Override
    public T findByNumeric(String campoId, Long id) {
        T objeto = null;
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            sessao.beginTransaction();
            Criteria criteria = sessao.createCriteria(classe);
            criteria.add(Restrictions.eq(campoId, id));
            objeto = (T) criteria.uniqueResult();
            Logger.getLogger(TarifadorDao.class.getName()).log(Logger.Level.INFO, objeto.toString());

            if (sessao.isOpen()) {
                sessao.close();
            }
        } catch (Exception e) {
            throw new HibernateException(e);
        }
        Logger.getLogger(TarifadorDao.class.getName()).log(Logger.Level.INFO, objeto.toString());

        return objeto;
    }

    @Override
    public Long countAllObject() {
        Long contador;
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            sessao.beginTransaction();
            Criteria criteria = sessao.createCriteria(classe);
            criteria.setProjection(Projections.rowCount());
            contador = (Long) criteria.uniqueResult();
            if (sessao.isOpen()) {
                sessao.close();
            }
        } catch (Exception e) {
            throw new HibernateException(e);
        }
        return contador;
    }

    @Override
    public List<T> listallparam(String campo, String param) {
        List<T> listaObjeto = null;
        String like = "%"+ param.trim() + "%";
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            sessao.beginTransaction();
            Criteria criteria = sessao.createCriteria(classe);
            criteria.add(Restrictions.ilike(campo, like ));
            listaObjeto = criteria.list();
            Logger.getLogger(TarifadorDao.class.getName()).log(Logger.Level.INFO, "Campo" +campo + " parametro : "+ like);
            if (sessao.isOpen()) {
                sessao.close();
            }
        } catch (Exception e) {
            if (sessao.isOpen()) {
                sessao.close();
            }
            throw new HibernateException(e);
        }
        Logger.getLogger(TarifadorDao.class.getName()).log(Logger.Level.INFO, listaObjeto.toString());

        return listaObjeto;
    }

    @Override
    public List<T> listAllBetweenDate(String dataInicio, String datafinal, String campoData) {
        List<T> lista = null;
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            sessao.beginTransaction();
            Criteria criteria = sessao.createCriteria(classe);
            criteria.add(Restrictions.between(campoData, dataInicio, datafinal));
            lista = criteria.list();
            if (sessao.isOpen()) {
                sessao.close();
            }
        } catch (Exception e) {
            if (sessao.isOpen()) {
                sessao.close();
            }
            throw new HibernateException(e);
        }
        return lista;

    }

    @Override
    public List<T> listall() {
        List<T> lista = null;
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            sessao.beginTransaction();
            Criteria criteria = sessao.createCriteria(classe);
            lista = criteria.list();
            if (sessao.isOpen()) {
                sessao.close();
            }
        } catch (Exception e) {
            if (sessao.isOpen()) {
                sessao.close();
            }
            throw new HibernateException(e);
        }
        return lista;
    }

    @Override
    public boolean delete(T objeto) {
        boolean valida;
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            transacao = sessao.beginTransaction();
            sessao.delete(objeto);
            transacao.commit();
            valida = true;
            if (sessao.isOpen()) {
                sessao.close();
            }
        } catch (Exception e) {
            if (sessao.isOpen()) {
                sessao.close();
            }
            throw new HibernateException(e);
        }

        return valida;
    }

    //Não salva usuario com o mesmo nome, e criptografa o mesmo    
    @Override
    public boolean saveUsuario(Usuario user) {
        boolean valida = false;
        usuarioTemp = new Usuario();
        criptrografa = new CriptografaSenha();
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            transacao = sessao.beginTransaction();
            usuarioTemp.setNome(user.getNome().toUpperCase());
            usuarioTemp.setPassword(criptrografa.criptografar(user.getPassword()).toUpperCase());
            sessao.saveOrUpdate(usuarioTemp);
            transacao.commit();
            valida = true;
            if (sessao.isOpen()) {
                sessao.close();
            }
        } catch (Exception e) {
            if (sessao.isOpen()) {
                sessao.close();
            }
            throw new HibernateException(e);
        }

        return valida;
    }

    @Override
    public List<Usuario> findAllUser() {
        List<Usuario> lista;
        Criteria criteria;

        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            sessao.beginTransaction();
            criteria = sessao.createCriteria(classe);
            lista = criteria.list();
            if (sessao.isOpen()) {
                sessao.close();
            }
        } catch (Exception e) {
            if (sessao.isOpen()) {
                sessao.close();
            }
            throw new HibernateException(e);
        }
        return lista;
    }
    //retorna usuario e senha decriptografado

    @Override
    public Usuario findUserDBciptografado(String nome) {
        Usuario usuarioTemp = new Usuario();
        Criteria criteria;

        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            sessao.beginTransaction();
            criteria = sessao.createCriteria(classe);
            criteria.add(Restrictions.like("nome", nome.toUpperCase()));
            usuarioTemp = (Usuario) criteria.uniqueResult();
            if (sessao.isOpen()) {
                sessao.close();
            }
        } catch (Exception e) {
            if (sessao.isOpen()) {
                sessao.close();
            }
            throw new HibernateException(e);

        }
        return usuarioTemp;
    }
}
